package easydst;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ProcessExecution {

	private String command;
	StringBuffer commandOutput;
	StringBuffer commandErr;

	public ProcessExecution() {
		new ProcessExecution("");
	}

	public ProcessExecution(String command) {
		setCommand(command);
		commandOutput = new StringBuffer();
		commandErr = new StringBuffer();
	}

	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	/**
	 * TODO Método para executar determinado comando a partir da classe Java
	 */
	public void execute() {

		String result;

		try {
			Process process = Runtime.getRuntime().exec(command);

			InputStream inputStream = process.getInputStream();
			InputStream errStream = process.getErrorStream();
			BufferedReader outputOfProcess;

			outputOfProcess = new BufferedReader(new InputStreamReader(
					inputStream));
			while ((result = outputOfProcess.readLine()) != null) {
				commandOutput.append(result + "\r\n");
			}

			outputOfProcess = new BufferedReader(new InputStreamReader(
					errStream));
			while ((result = outputOfProcess.readLine()) != null) {
				commandErr.append(result + "\r\n");
			}

			process.waitFor();

			outputOfProcess.close();
			errStream.close();
			inputStream.close();
			process.getOutputStream().close();

		} catch (IOException errorMensage) {
			commandErr.append(errorMensage.toString());
		} catch (InterruptedException errorMensage) {
			commandErr.append(errorMensage.toString());
		}

	}

	public StringBuffer getCommandOutput() {
		return commandOutput;
	}

	public StringBuffer getCommandErr() {
		return commandErr;
	}

}
